package org.ww.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.ww.order.bean.Order;
import org.ww.order.bean.PayLog;
import org.ww.order.mapper.PayLogMapper;
import org.ww.order.service.OrderService;
import org.ww.order.service.PayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.ww.order.utils.HttpClient;
import org.ww.servicebase.exceptionhandler.GuliException;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author ww
 * @since 2020-11-11
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {
    @Autowired
    private OrderService orderService;

    /**
     * 根据订单id生成微信支付二维码
     * @param orderNo
     * @return
     */
    @Override
    public Map createNative(String orderNo) {
        try {
            //1 根据订单id查询订单信息
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            Order orderInfo = orderService.getOne(wrapper);
            //2 使用map生成二维码所需要的参数
            Map m=new HashMap();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("nonce_str", WXPayUtil.generateNonceStr()); //随机生成的id
            m.put("body", orderInfo.getCourseTitle());
            m.put("out_trade_no", orderNo);
            m.put("total_fee", orderInfo.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");//回调地址
            m.put("trade_type", "NATIVE");
            //3 HttpClient来根据url访问第三方接口并且传递参数
            HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行请求发送
            client.post();
            //4 得到发送请求返回的结果
            //返回的结果是以xml形式进行返回的
            String xml = client.getContent();
            //将xml形式转换成map类型
            Map<String,String> resultMap=WXPayUtil.xmlToMap(xml);

            //将结果重新进行封装
            Map map=new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", orderInfo.getCourseId());
            map.put("total_fee", orderInfo.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));//生成微信的状态码
            map.put("code_url", resultMap.get("code_url"));//生成微信的url
            return map;
        } catch (Exception e) {
            throw new GuliException(20001,"生成微信二维码失败！");
        }
    }

    /**
     * 根据订单id查询订单状态
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, String> getOrderStatus(String orderNo) {
        try{
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map
            //7、返回
            return resultMap;
        } catch (Exception e) {
            throw new GuliException(20001,"支付出错了");
        }
    }

    /**
     * 更新订单表订单状态,向支付表添加支付记录
     * @param map
     */
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //从map中获取订单号
        String orderNo = map.get("out_trade_no");

        //1 根据订单id查询订单信息
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order orderInfo = orderService.getOne(wrapper);

        //2 更新订单表订单状态
        if(orderInfo.getStatus()==1){return;}

        orderInfo.setStatus(1);
        orderService.updateById(orderInfo);

        //3 添加支付订单记录
        PayLog payLog=new PayLog();
        payLog.setOrderNo(orderInfo.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型
        payLog.setTotalFee(orderInfo.getTotalFee());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));//订单流水号
        payLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(payLog);//插入到支付日志表
    }
}

